package com.cans.config.shiro;


import com.cans.model.pms.SysMenu;
import com.cans.model.pms.SysRole;
import com.cans.model.pms.SysUser;
import com.cans.service.pms.api.ISysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

/**
 * @author shencan
 * @date 2019/8/15 17:11
 * @description shiro核心类
 */
public class ShiroRealm extends AuthorizingRealm {

    @Resource
    private ISysUserService sysUserService;

    /**
     * 鉴权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //如果身份认证的时候没有传入User对象，这里只能取到userName
        //也就是SimpleAuthenticationInfo构造的时候第一个参数传递需要User对象
        SysUser user = (SysUser) principals.getPrimaryPrincipal();

        for (SysRole role : user.getRoleList()) {
            authorizationInfo.addRole(role.getCode());

            for (SysMenu p : role.getMenuList()) {
                authorizationInfo.addStringPermission(p.getCode());
            }
        }
        return authorizationInfo;
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
        //获取用户的输入的账号.
        String username = (String) token.getPrincipal();
        System.out.println(token.getCredentials());
        //通过username从数据库中查找 User对象.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        SysUser user = sysUserService.getUserFull(username);

        System.out.println("----->>user=" + user);

        if (user == null) {
            return null;
        }

        // 使用用户名获得盐
        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUsername());
        // 创建SimpleAuthenticationInfo对象，并且把username和password等信息封装到里面
        // 用户密码的比对是Shiro帮我们完成的

        return new SimpleAuthenticationInfo(user, user.getPassword(), credentialsSalt, this.getName());
    }
}
